﻿using Modules.Project;
using PmSoft;

namespace ManagementApi.Authorizers
{
    /// <summary>
    /// 项目数据权限验证
    /// </summary>
    [UseDI(ServiceLifetime.Scoped)]
    public class ProjectGroupOwnAuthorizer
    {
        private readonly ProjectOwnAuthorizer projectOwnAuthorizer;
        private readonly ProjectGroupService projectGroupService;

        /// <summary>
        /// 班组数据权限验证
        /// </summary>
        /// <param name="projectOwnAuthorizer"></param>
        /// <param name="projectGroupService"></param>
        public ProjectGroupOwnAuthorizer(ProjectOwnAuthorizer projectOwnAuthorizer,
            ProjectGroupService projectGroupService)
        {
            this.projectOwnAuthorizer = projectOwnAuthorizer;
            this.projectGroupService = projectGroupService;
        }

        /// <summary>
        /// 检查并抛出数据权限验证失败信息
        /// </summary>
        /// <param name="projectGroupId"></param>
        /// <exception cref="OwnAuthorizationFailedException"></exception>
        public void CheckAndThrowIfOwnAuthenticationFailed(int projectGroupId)
        {
            var projectGroup = projectGroupService.GetProjectGroup(projectGroupId) ?? throw new OwnAuthorizationFailedException();
            var projectId = projectGroup.ProjectId;
            projectOwnAuthorizer.CheckAndThrowIfOwnAuthenticationFailed(projectId);
        }

        /// <summary>
        /// 检查并抛出数据权限验证失败信息
        /// </summary>
        /// <param name="projectGroupIds"></param>
        public void CheckAndThrowIfOwnAuthenticationFailed(IEnumerable<int> projectGroupIds)
        {
            foreach (int projectGroupId in projectGroupIds)
                CheckAndThrowIfOwnAuthenticationFailed(projectGroupId);
        }
    }
}